import React, { PureComponent } from "react";
import {
  Text,
  View,
  Image,
  TextInput,
  Alert,
  ScrollView,
  FlatList,
  Platform,
  TouchableOpacity,
  Keyboard,
  StyleSheet,
  RefreshControl
} from "react-native";
import {
  statusBarHeight,
  safeAreaBottomHeight,
  LoginToken,
  screenHeight
} from "../../util/AdapterUtil";
import actions from "../../models/actions";
import { connect } from "react-redux";
import NavigationBar from "../../components/navigationBar";
import image from "../../assets/image";
import FlatListEmpty from "../../components/FlatListEmpty";
import FlatListFooter from "../../components/FlatListFooter";
import {
  ClassicsHeader,
  SmartRefreshControl
} from "react-native-smartrefreshlayout";
import ImageView from "../../components/ImageView";
import * as requestApi from "../../util/requestApi";
import _ from "lodash";

class CarBusinessListScreen extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isRefreshing: false,
      searchText: "",
      data: [],
      loading: false,
      hasMore: true
    };
    this.debouncedOnSubmitText = _.debounce(this.onSubmitText.bind(this), 300);
    this.debouncedGetData = _.debounce(this.getData.bind(this,this.state.searchText,false), 300);
  }

  componentWillUnmount() {}

  componentDidMount() {
    this.getData("");
  }

  render() {
    const { searchText, data, hasMore } = this.state;
    return (
      <View style={{ flex: 1, backgroundColor: "#F9F9F9" }}>
        <NavigationBar
          navigation={this.props.navigation}
          isBack={true}
          title={"汽配商"}
        />

        {/*搜索框*/}
        <View
          style={{
            backgroundColor: "#F9F9F9",
            paddingLeft: 10,
            paddingRight: 10,
            paddingTop: 10,
            paddingBottom: 10,
            flexDirection: "row",
            alignItems: "center",
            width: "100%",
            height: 60,
            zIndex: 1000
          }}
        >
          <TextInput
            style={{
              flex: 1,
              height: 40,
              paddingLeft: 50,
              paddingRight: 20,
              paddingVertical: 0,
              borderTopLeftRadius: 10,
              borderBottomLeftRadius: 10,
              backgroundColor: "#E6E6E6"
            }}
            ref={e => {
              this.searchTextInput = e;
            }}
            value={searchText}
            autoFocus={false}
            placeholder={"请输入搜索内容"}
            placeholderTextColor={"#989898"}
            selectionColor={"#4A90E2"}
            autoCapitalize={"none"}
            underlineColorAndroid="transparent"
            onChangeText={text => {
              this.setState({
                searchText: text
              });
              this.debouncedOnSubmitText();
            }}
            returnKeyType={"search"}
            onSubmitEditing={(event) => {
                if (event.nativeEvent.text.trim().length == 0) {
                    Toast.show("请输入搜索内容", 500);
                    this.setState({
                        searchText: ""
                    });
                }else {
                    this.onSubmitText();
                }
            }}
          />

          <TouchableOpacity
            style={{
              flexDirection: "row",
              justifyContent: "center",
              alignItems: "center",
              backgroundColor: "#4A90E2",
              borderTopRightRadius: 10,
              borderBottomRightRadius: 10,
              width: 60,
              height: "100%"
            }}
            onPress={() => {
              if (searchText.trim().length == 0) {
                Toast.show("请输入搜索内容", 500);
                this.setState({
                    searchText: ""
                });
              }else {
                this.onSubmitText();
              }
            }}
          >
            <Text style={{ color: "#fff", fontSize: 18 }}>搜索</Text>
          </TouchableOpacity>

          <Image
            style={{
              position: "absolute",
              left: 32,
              width: 20,
              height: 20
            }}
            source={image.icon_search}
          />
          {searchText.trim().length === 0 ? null : (
            <TouchableOpacity
              style={{ position: "absolute", right: 80, width: 18, height: 18 }}
              onPress={() => {
                this.clearTextInput();
              }}
            >
              <Image
                style={{
                  width: 18,
                  height:18
                }}
                source={image.clear}
              />
            </TouchableOpacity>
          )}
        </View>

        <ScrollView
          style={{ flex: 1 }}
          alwaysBounceVertical={true}
          refreshControl={
            Platform.OS == "ios" ? (
              <RefreshControl
                refreshing={this.state.isRefreshing}
                onRefresh={() => {
                  this._onRefresh();
                }}
                backgroundColor={"#F9F9F9"}
              />
            ) : (
              <SmartRefreshControl
                ref={ref => (this.rc = ref)}
                renderHeader={<ClassicsHeader primaryColor="#F9F9F9" />}
                onRefresh={() => {
                  this._onRefresh();
                }}
                onLoadMore={() => {
                  this.getData(searchText, false);
                }}
              />
            )
          }
        >
          <FlatList
            style={{ backgroundColor: "#fff" }}
            scrollEnabled={false}
            data={this.state.data}
            horizontal={false}
            keyExtractor={(item, index) => index.toString()}
            renderItem={this._renderItem}
            ListEmptyComponent={() => <FlatListEmpty />}
            ListFooterComponent={() => (
              <FlatListFooter
                isShowBottom={true}
                show={data && data.length > 10 ? true : false}
                hasMore={hasMore}
              />
            )}
            onEndReached={() => {
              if (data.length >= 10) {
                //大于等于10 说明到了底部
                this.debouncedGetData();
              }
            }}
            onEndReachedThreshold={1}
          />
        </ScrollView>
        <View style={{ height: safeAreaBottomHeight }} />
      </View>
    );
  }

  //下拉刷新
  _onRefresh = () => {
    this.setState({ isRefreshing: true });
    this.getData(this.state.searchText);

    // setTimeout(() => {
    // }, 1000);
  };

  // 提交搜索  data是搜索历史逻辑 当前未用到
  onSubmitText = data => {
    //Keyboard.dismiss();
    const { searchText } = this.state;
    let keyword;
    if (data != null && typeof data != "undefined") {
      keyword = data;
      //发起搜索请求
      this.getData(keyword);
    } else {
      keyword = searchText;
      //发起搜索请求
      this.getData(keyword);
    }
  };

  getData = (keyword = this.state.searchText, isFirstPage = true) => {
    Loading.show();
    const { data, loading, hasMore } = this.state;
    if (isFirstPage || data == null || data.length === 0 || data.length < 10) {
      // 第一页
      requestApi
        .getSearchListData({ companyName: keyword, page: 1 })
        .then(res => {
          this._finishRefresh();
          this.setState({
            data: res ? res : [],
            hasMore: true
          });
        })
        .catch(() => {
          this._finishRefresh();
        });
    } else {
      if (
        data == null ||
        data.length === 0 ||
        data.length < 10 ||
        loading ||
        !hasMore
      ) {
        return;
      }
      this.setState({
        loading: true
      });
      let page = data.length / 10 + 1;
      requestApi
        .getSearchListData({ companyName: keyword, page: page })
        .then(res => {
          this._finishRefresh();
          if (res != null || res.length == 0) {
            Toast.show("没有更多数据了", 500);
          }
          let _data = [...data, ...res];
          let _hasMore = res.total === _data.length ? false : true;
          this.setState({
            data: _data,
            hasMore: _hasMore
          });
        })
        .catch(e => {
          this._finishRefresh();
        });
    }
  };

  _finishRefresh = () => {
    Loading.hide(); //延时 0.2秒关闭
    this.setState({
      loading: false
    });
    Platform.OS == "ios"
      ? this.setState({ isRefreshing: false })
      : this.rc && this.rc.finishRefresh();
  };

  // 清空输入框内容
  clearTextInput = () => {
    this.searchTextInput && this.searchTextInput.clear();
    this.setState({
      searchText: "",
    });
    this.searchTextInput && this.searchTextInput.focus();
    this.onSubmitText("");
  };

  _renderItem = ({ item }) => (
    <MyListItem onPressItem={this._onPressItem.bind(this)} item={item} />
  );

  _onPressItem = item => {
    //alert(id);
  };
}

class MyListItem extends PureComponent {
  _onPress = () => {
    this.props.onPressItem(this.props.item);
  };

  render() {
    return (
      <View style={{ height: 101, width: "100%" }}>
        <View
          style={{
            flexDirection: "row",
            height: 100,
            width: "100%",
            marginLeft: 10,
            marginTop: 2,
            marginRight: 10,
            marginBottom: 2,
            alignItems: "center"
          }}
        >
          <ImageView
            source={{
              uri:
                "http://cdn.traceche.com/" + this.props.item.companyHeadPicUrl
            }}
            style={{ width: 60, height: 60 }}
          />

          <View
            style={{
              height: 60,
              marginLeft: 10,
              paddingTop: 2,
              marginRight: 10,
              paddingBottom: 2,
              justifyContent: "center"
            }}
          >
            <Text style={{ color: "#606060" }}>
              {this.props.item.companyName}
            </Text>
            <Text style={{ color: "#AAAAAA" }}>
              主营：{this.props.item.business}
            </Text>
            <Text style={{ color: "#AAAAAA" }}>
              电话：{this.props.item.phone}
            </Text>
            <Text style={{ color: "#AAAAAA" }}>
              地址：{this.props.item.address}
            </Text>
          </View>
        </View>

        <View
          style={{
            marginLeft: 80,
            height: 1,
            backgroundColor: "#DDDDDD",
            transform: [{ scaleY: 0.5 }]
          }}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({});

export default connect(
  ({ userInfo }) => ({
    userInfo
  }),
  {
    getSearchListData: actions.getSearchListData
  }
)(CarBusinessListScreen);

/*[{
	"companyId": 5,
	"companyType": 2,
	"companyName": "测试",
	"contact": "网国亮",
	"phone": "18782228298",
	"business": "汽车配件",
	"address": "四川成都",
	"companyHeadPicUrl": "Fh32t9Syu4hpUaXrLyo8ytjDY8CI"
}, {
	"companyId": 8,
	"companyType": 2,
	"companyName": "测试",
	"contact": "网国亮",
	"phone": "18782228298",
	"business": "测试",
	"address": "四川成都",
	"companyHeadPicUrl": "FsdW-jld7nBLHU3aJAzzB9S-MT98"
}]*/
